package cn.dgut.loginManager;

import cn.dgut.Entity.User;
import cn.dgut.Utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/checkServlet")
public class checkServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            int flag=0;
           JDBCUtils utils = new JDBCUtils();
            String aa= request.getParameter("user_name");
            String bb= request.getParameter("password");

       String  sql = "select * from User";

        JDBCUtils jdbcUtils = new JDBCUtils();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = jdbcUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            //5.执行sql
            rs = stmt.executeQuery(sql);
            while(rs.next()) {
                User temp = new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6));
                if(temp.getUser_name().equals(aa)&&temp.getUser_passwd().equals(bb)) flag=1;
                if(temp.getUser_name().equals(aa)&&(!temp.getUser_passwd().equals(bb))) flag=2;
            }
            //提交事务
            conn.commit();
        } catch (Exception e) {
            //事务回滚
            try {
                if(conn != null) {
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            jdbcUtils.close(stmt,conn);
        }

       // if(flag==1) response.sendRedirect("http://localhost:8084/backstage/index.jsp");

        response.setContentType("application/json,charset=utf-8");
        String strJson = "{\"flag\":\""+flag+"\"}";
        response.getWriter().println(strJson);

        }

}
